const express = require("express");
// 有什么难的，express, mysql, sequelize, zpqy, sequelize-cli 所有技术都只是我的工具而已，怕什么？
const { Article } = require("../../models");
const { Op } = require("sequelize");
const { success, fail } = require("../../utils/response");
const {NotFound, BadRequest} = require('http-errors')

const router = express.Router();
// 查询文章-带分页
router.get("/", async (req, res) => {
  try {
    const { pageNum, pageSize } = req.query;
    const conditions = getConditions(req);
    const { count, rows } = await Article.findAndCountAll(conditions);
    success(res, "获取成功", {
      pageNum,
      pageSize,
      count,
      list: rows,
    });
  } catch (error) {
    // console.log("自主抛出的错误！", error.name);
    fail(res, error);
  }
});
// 获取参数
function getConditions(req) {
  const { keywords, pageNum, pageSize } = req.query;
  const conditions = {
    where: {},
  };
  // 分页参数，没传分页 就是查询所有
  const page = Math.abs(pageNum);
  const size = Math.abs(pageSize);
  if (page && size) {
    conditions.offset = (page - 1) * size;
    conditions.limit = size;
  }
  // 处理普通参数
  if (keywords) {
    conditions.where.title = {
      [Op.like]: `%${keywords}%`,
    };
  }
  return conditions;
}
// 查询文章-无分页
router.get("/all", async (req, res) => {
  try {
    const { keywords } = req.query;
    let where = {};

    if (keywords) {
      where.title = {
        [Op.like]: `%${keywords}%`,
      };
    }
    const raws = await Article.findAll({ where });
    success(res, "获取成功", raws);
  } catch (error) {
    fail(res, error);
  }
});
// 查询文章详情
router.get("/:id", async (req, res) => {
  try {
    const { id } = req.params;
    if(!id) {
      throw BadRequest('文章id不能为空')
    }
    const article = await Article.findByPk(id);
    if (!article) {
      throw NotFound('未找到此文章')
    }
    success(res, "获取成功", article);
  } catch (error) {
    fail(res, error);
  }
});
// 增加文章
router.post("/", async (req, res) => {
  try {
    const { title, content } = req.body;
    const article = await Article.create({ title, content });
    console.log("article", article);
    success(res, "success", article);
  } catch (error) {
    fail(res, error);
  }
});
// 修改文章
router.put("/:id", async (req, res) => {
  try {
    const { id } = req.params;
    const { title, content } = req.body;
    const article = await Article.findByPk(id)
    if (!article) {
      throw NotFound("未找到此文章");
    }
    let data = {}
    if(title !== "") {
      data.title = title
    }
    if(content !== null) {
      data.content = content
    }
    const [num] = await Article.update(
      data,
      {
        where: {
          id,
        },
      }
    );
    success(res, "success", num);
  } catch (error) {
    fail(res, error);
  }
});
// 删除文章
router.delete("/:id", async (req, res) => {
  try {
    const { id } = req.params;
    const article = await Article.destroy({
      where: { id },
    });
    if (!article) {
      throw NotFound("未找到此文章");
    }
    success(res, "success",article);
  } catch (error) {
    fail(res, error);
  }
});

module.exports = router;
